package com.jlf.tool.sensitive;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.jlf.tool.sensitive.annotation.Sensitive;
import com.jlf.tool.sensitive.annotation.SensitiveType;

import java.io.IOException;
import java.util.Objects;


/**
 * json的脱敏处理
 *
 * @author 吴建荣 2019-01-21
 */
public class JsonSensitiveSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private SensitiveType type;
    public JsonSensitiveSerializer(){}
    public JsonSensitiveSerializer(SensitiveType type){
        this.type = type;
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        switch (this.type) {
            case NAME:
                jsonGenerator.writeString(Desensitize.name(s));
                break;
            case ID_CARD:
                jsonGenerator.writeString(Desensitize.around(s, 2, 2));
                break;
            case MOBILE:
                jsonGenerator.writeString(Desensitize.around(s, 3, 2));
                break;
            case ADDRESS:
                jsonGenerator.writeString(Desensitize.address(s, 4));
                break;
            case EMAIL:
                jsonGenerator.writeString(Desensitize.email(s));
                break;
            case ALL:
                jsonGenerator.writeString(Desensitize.all(s));
                break;
            default:
                break;
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            // 为空直接跳过
            if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
                // 非 String 类直接跳过
                Sensitive sensitive = beanProperty.getAnnotation(Sensitive.class);
                if (sensitive == null) {
                    sensitive = beanProperty.getContextAnnotation(Sensitive.class);
                }
                if (sensitive != null) {
                    // 如果能得到注解，就将注解的 value 传入 SensitiveInfoSerialize
                    return new JsonSensitiveSerializer(sensitive.value());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(beanProperty);
    }
}
